package com.emm.yixun.system.service.impl;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jws.WebService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.enums.ModelEnum;
import com.emm.yixun.basic.service.CompanyService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.DepartmentService;
import com.emm.yixun.basic.service.ModelKeyService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.Company;
import com.emm.yixun.common.model.Department;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.DepartmentDto;
import com.emm.yixun.common.model.dto.DepartmentModel;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.dto.UserModel;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.UserStatusEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.common.utils.PasswordUtil;
import com.emm.yixun.system.service.DepartmentServiceFacade;

@Service
@WebService(name="com.emm.yixun.system.service.DepartmentServiceFacade")
public class DepartmentServiceFacadeImpl implements DepartmentServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private DepartmentService service;
	
	@Autowired
	private UserService userService;
	
	@Resource
	private ModelKeyService modelKeyService;
	@Autowired
	private DataPermissionService dataPermissionService;
	
	@Autowired
	private CompanyService companyService;

	@Override
	public Response<DepartmentDto> save(DepartmentDto dto) {
		Response<DepartmentDto> response=new Response<DepartmentDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			if(dto.getParentId()==-1){
				//1级组织机构
				String permissionCode=modelKeyService.next(ModelEnum.DEPARTMENT);
				dto.setPermissionCode(permissionCode);;
			}
			DepartmentDto mDto=service.create(dto);
			//维护机构权限code
			if(dto.getParentId()>0){
				Department department=service.selectById(new Long(dto.getParentId()));
				DepartmentDto updateDto=new DepartmentDto();
				String permissionCode= "";
				if(department==null){
				    permissionCode=modelKeyService.next(ModelEnum.DEPARTMENT);
				    updateDto.setParentId(-1L);
				    Company company = companyService.selectById(dto.getParentId());
				    updateDto.setSubcompanyCode(company.getCompanyCode());
				}else{
				    permissionCode=department.getPermissionCode()==null?"":department.getPermissionCode();
				}
				permissionCode=permissionCode+"_"+mDto.getId();
				updateDto.setId(mDto.getId());
				updateDto.setPermissionCode(permissionCode);
				service.update(updateDto);
			}
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(DepartmentDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto /*|| null==dto.getId()*/){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=service.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			DepartmentDto mDto=new DepartmentDto();
			mDto.setId(id);
			int count=service.destroy(mDto);
			if(count>0){
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<Department> findById(Long id) {
		Response<Department> response=new Response<Department>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			Department entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<Department> findByDto(DepartmentDto dto) {
		ResponseList<Department> response=new ResponseList<Department>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			
			//数据权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(), dto.getResourcesCode(), dto.getPrefix(), dto.getColumnName());
				String [] dataPermissionArr = dataPermission.split(":");
				if("00".equals(dataPermissionArr[0])){
					response.setResultMessage(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					response.setSuccess(false);
					return response;
				}
				dto.setDataPermission(dataPermissionArr[1]);
			}
			
			List<Department> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<Department> findPageByDto(DepartmentDto dto, Integer begin,Integer row) {
		Page<Department> response=new Page<Department>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<Department> page = service.getPageModel(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Boolean> deleteByParentId(Long parentId) {
		Response<Boolean> response=new Response<Boolean>();
		try {
			if(null==parentId){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("parentId"));
				return response;
			}
			Department department=service.selectById(parentId);
			if(null==department){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("部门"));
				return response;
			}
			//删除部门
			deleteDetp(parentId);
			response.success(Boolean.TRUE);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除部门数据错误：{}",e);
		}
		return response;
	}
	
	private void deleteDetp(Long parentId){
		//删除部门
		DepartmentDto dtt=new DepartmentDto();
		dtt.setId(parentId);
		int deleteParentCount=service.destroy(dtt);
		if(deleteParentCount<=0)return;
		//删除人员
		deleteUserByDeptId(parentId);
		
		DepartmentDto departmentDto=new DepartmentDto();
		departmentDto.setParentId(parentId);
		List<Department> list=service.selectListByDto(departmentDto);
		if(null==list || list.size()==0)return;
		//删除子部门
		for(Department dt : list){
			DepartmentDto child=new DepartmentDto();
			child.setId(dt.getId());
			int deleteCount=service.destroy(child);
			if(deleteCount<=0)continue;
			//删除人员
			deleteUserByDeptId(dt.getId());
			deleteDetp(dt.getId());
		}
	}
	
	private void deleteUserByDeptId(Long deptId){
		UserDto userDto=new UserDto();
		userDto.setUserDepartmentId(deptId);
		List<User> list=userService.selectListByDto(userDto);
		if(null==list || list.size()==0)return;
		for(User u : list){
			UserDto row=new UserDto();
			row.setId(u.getId());
			userService.destroy(row);
		}
	}
	
	/**
	 * 部门信息导入
	 */
	public Response<String> departmentImport(List<DepartmentModel> list, User user){
		Response<String> response = new Response<String>();
		try {
			for (DepartmentModel model : list) {
				DepartmentDto entity = new DepartmentDto();
				//部门code
				entity.setDepartmentCode(model.getDepartmentCode());
				entity.setDepartmentName(model.getDepartmentName());
				if (StringUtils.isNotBlank(model.getParentCode())) {
					Department department = getDepartmentDtoByCode(null, model.getParentCode());
					entity.setSubcompanyCode(model.getParentCode());
					entity.setParentId(department.getId());
					entity.setPermissionCode(department.getDepartmentCode()+"_"+department.getId());
				} else {
					if("本部-绿城东方建设管理有限公司".equals(model.getCompany())) {
						entity.setSubcompanyCode("LCDF001");
						entity.setParentId(-1L);
					} else {
						Department department = getDepartmentDtoByCode(model.getCompany(), null);
						entity.setSubcompanyCode(model.getParentCode());
						entity.setParentId(department.getId());
					}
					entity.setPermissionCode(modelKeyService.next(ModelEnum.DEPARTMENT));
				}
				entity.setMerchantId(user.getMerchantId());
				entity.setCanceled("0");
				entity.setCreateUserId(1L);
				entity.setUpdateUserId(1L);
				entity.setUpdateTime(Calendar.getInstance().getTime());
				entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
				service.create(entity);
			} 
			response.success();
		} catch (Exception e) {
			logger.error("部门信息导入失败", e);
			response.fail("部门信息导入失败", e.getMessage());
		}
		return response;
	}
	/**
	 * 跟进部门code查询部门信息
	 * @param code
	 * @return
	 */
	private Department getDepartmentDtoByCode(String name, String code) {
		DepartmentDto entity = new DepartmentDto();
		entity.setDepartmentName(name);
		entity.setDepartmentCode(code);
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		Department department = service.selectByDto(entity);
		return department;
	}
	
	/**
	 * 用户信息导入
	 */
	public Response<String> userInfoImport(List<UserModel> list, Long merchantId){
		Response<String> response = new Response<String>();
		try {
			for (UserModel model : list) {
				//获取用户id
				Long userId = getUserIdByUserName(model.getUserAccount(), model.getUserName(), model.getUserPhone(), merchantId);
				
				UserDto entity = new UserDto();
				entity.setOaUserCode(model.getOaUserCode());
				entity.setPosition(model.getPosition());
				entity.setEntryTime(DateUtils.StringToDate(model.getEntryTime(), DateStyle.YYYY_MM_DD));
				entity.setBirthday(DateUtils.StringToDate(model.getBirthday(), DateStyle.YYYY_MM_DD));
				entity.setSex("男".equals(model.getSex())?"0":"1");
				entity.setEmail(model.getEmail());
				entity.setUserPhone(model.getUserPhone());
				entity.setUpdateUserId(1L);
				entity.setUpdateTime(Calendar.getInstance().getTime());
				entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
				entity.setUserStatus(UserStatusEnum.IN_USE.getNo());
				//获取部门ID和CODE
				//Map<String, String> map = getDepartmentByName(model.getCompany(), model.getParentName(), model.getDepartmentName());
				Department department = getDepartmentDtoByCode(null, model.getDepartmentCode());
				entity.setUserDepartmentId(department.getId());
				entity.setUserDepartmentPath(model.getDepartmentCode());
				//已存在则更新，不存在就新增
				if(userId != null) {
					entity.setId(userId);
					userService.editById(entity);
				} else {
					entity.setIsAdmin("0");
					entity.setUserPassword(PasswordUtil.md5Hex("x1234567"));
					entity.setUserAccount(model.getUserAccount());
					entity.setUserName(model.getUserName());
					entity.setUserCode(modelKeyService.next(ModelEnum.USER));
					entity.setCreateUserId(1L);
					entity.setMerchantId(merchantId);
					entity.setSkin("skin-0");
					entity.setRemark("excel导入");
					userService.create(entity);
				}
			} 
			response.success();
		} catch (Exception e) {
			logger.error("用户信息导入失败", e);
			response.fail("用户信息导入失败", e.getMessage());
		}
		return response;
	}
	/**
	 * 跟进用户姓名和账号查询用户id
	 * @param userAccount
	 * @param userName
	 * @return
	 */
	private Long getUserIdByUserName(String userAccount, String userName, String userPhone, Long merchantId) {
		UserDto entity = new UserDto();
		entity.setUserAccount(userAccount);
		entity.setUserName(userName);
		entity.setUserPhone(userPhone);
		entity.setMerchantId(merchantId);
		entity.setDelFlag(DelFlagEnum.DEL.getNo());
		entity.addDesc("update_time");
		List<User> list = userService.selectByDtoList(entity);
		if(list == null || list.size() == 0) {
			return null;
		}
		User user = list.get(0);
		return user.getId();
	}
	
	/**
	 * 通过部门名称获取部门信息
	 * @return
	 */
	private Map<String, String> getDepartmentByName(String company, String parentName, String departmentName){
		Map<String, String> resMap = new HashMap<String, String>();
		DepartmentDto entity = new DepartmentDto();
		if("本部-绿城东方建设管理有限公司".equals(company)) {
			if(parentName == null ) {
				entity.setSubcompanyCode("LCDF001");
			} else if (!departmentName.equals(parentName)) {
				Department dt = getDepartmentDtoByParentCode(parentName, "DF001-021");
				entity.setSubcompanyCode(dt.getDepartmentCode());
			} else if (departmentName.equals(parentName)) {
				entity.setSubcompanyCode("DF001-021");
			}
		} else {
			Department companyInfo = getDepartmentDtoByCode(company, null);
//			if("项目公司领导".equals(departmentName)) {
				entity.setSubcompanyCode(companyInfo.getDepartmentCode());
//			} else {
//				Department dt = getDepartmentDtoByParentCode("项目公司领导", companyInfo.getDepartmentCode());
//				entity.setSubcompanyCode(dt.getDepartmentCode());
//			}
		}
		entity.setDepartmentName(departmentName);
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		Department department = service.selectByDto(entity);
		if(department == null) {
			System.out.println(company+"==="+departmentName);
		}
		resMap.put("id", department.getId().toString());
		resMap.put("code", department.getDepartmentCode());
		return resMap;
	}
	
	/**
	 * 根据上级部门code和本部门名称，查询本部门code
	 * @param code
	 * @return
	 */
	private Department getDepartmentDtoByParentCode(String name, String parentCode) {
		DepartmentDto entity = new DepartmentDto();
		entity.setSubcompanyCode(parentCode);
		entity.setDepartmentName(name);
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		Department department = service.selectByDto(entity);
		return department;
	}
}
